﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands
{
    using Galaktika.BI.Silverlight.Controls.Data;
    using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
    using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.Services;
    using Galaktika.BI.Runtime.Services;
    using Galaktika.BI.Extensibility.Dom.Dac;
    using Microsoft.AnalysisServices.AdomdClient;
    using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;

    public abstract class TransactionCommand : ServerCommand
    {
        protected TransactionCommand(InvokeSchema invoker)
            : base(invoker.CommandId)
        {
            this.ContextId = invoker[KnownInvokeArgs.ContextId];
            this.ConnectionName = invoker[KnownInvokeArgs.ConnectionName];

            if (this.ContextId == null)
            {
                throw new ArgumentNullException(KnownInvokeArgs.ContextId);
            }
            if (this.ConnectionName == null)
            {
                throw new ArgumentNullException(KnownInvokeArgs.ConnectionName);
            }
        }

        public string ContextId { get; private set; }
        public string ConnectionName { get; private set; }

        public override InvokeResultSchema Invoke()
        {
            InvokeResultSchema res = new InvokeResultSchema(base.Id);
            res.ContentType = KnownContentTypes.Error;

            DataBinder binder = DataBinder.Current;
            BrickConnection brickConn = binder.GetNamedObject(this.ConnectionName) as BrickConnection;
            if (brickConn == null)
            {
                res.Content = string.Format(Localization.Msg_ConnectionNotFound, this.ConnectionName);
                return res;
            }
            IBindingContext context = binder.GetContext(this.ContextId);
            if (context == null)
            {
                res.Content = string.Format(Localization.Msg_BindingContextNotFound, this.ContextId);
                return res;
            }

            IExecutionContext exe = (IExecutionContext)context.Services.GetService(typeof(IExecutionContext));
            if (exe != null)
            {
                string connectionString = exe.Parse(context, brickConn.ConnectionString);
                AdomdConnection conn = AdomdConnectionPool.GetConnection(connectionString);
                string cmdText = this.CreateCommand();
                using (AdomdCommand cmd = new AdomdCommand(cmdText, conn))
                {
                    cmd.ExecuteNonQuery();
                }

            }

            res.ContentType = KnownContentTypes.Empty;
            return res;
        }

        protected abstract string CreateCommand();
    }
}
